package com.irate.activity;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.facebook.widget.WebDialog;
import com.irate.dao.UserDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.provider.ContentManager;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebook.OnPublishListener;
import com.sromku.simple.fb.entities.Feed;

public class ShareActivity extends Activity {

	protected SimpleFacebook fb;
	protected ProgressDialog dialog;
	protected UserDAO userDAO;
	protected String message;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_share);
		init();
		execute();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		if (message.equals("login"))
			startActivity(new Intent(ShareActivity.this, WelcomeActivity.class));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		fb.onActivityResult(this, requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void init() {
		userDAO = new UserDAO();
		fb = SimpleFacebook.getInstance(this);
		message = getIntent().getStringExtra("message");
	}

	private void execute() {

		if (!fb.isLogin()) {
			fb.login(new OnLoginListener() {

				@Override
				public void onFail(String reason) {
					startActivity(new Intent(ShareActivity.this,
							WelcomeActivity.class));
				}

				@Override
				public void onException(Throwable throwable) {
					startActivity(new Intent(ShareActivity.this,
							WelcomeActivity.class));
				}

				@Override
				public void onThinking() {

				}

				@Override
				public void onNotAcceptingPermissions() {
					startActivity(new Intent(ShareActivity.this,
							WelcomeActivity.class));
				}

				@Override
				public void onLogin() {

					doWhenLogined();
				}

			});
		} else {
			doWhenLogined();
		}

	}

	private void doWhenLogined() {
		if (message.equals("login")) {
			dialog = ProgressDialog.show(ShareActivity.this, getResources()
					.getString(R.string.login),
					getResources().getString(R.string.loading), true);

			userDAO.loginWithFacebook(fb.getAccessToken(),
					handlerLoginFacebook, ShareActivity.this, dialog);
		}
		if (message.equals("share")) {
			publishFeedDialog();
		}

	}

	AsyncHttpResponseHandler handlerLoginFacebook = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");

			userDAO.parsedata(new String(response));

			if (ContentManager.getInstance().isLogin()) {
				startActivity(new Intent(ShareActivity.this, MainActivity.class));
				finish();
			} else {
				Toast.makeText(ShareActivity.this,
						getResources().getString(R.string.login_error),
						Toast.LENGTH_SHORT).show();
			}

		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");

			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(ShareActivity.this,
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}

			startActivity(new Intent(ShareActivity.this, WelcomeActivity.class));
		}
	};

	private void publishFeedDialog() {

		Bundle params = new Bundle();

		params.putString("name", "Irate");
		params.putString("message","kjgfdjgkdfhjkdfk");
	    params.putString("caption", "The Facebook SDK for Android makes it <br/> easier and faster to develop Facebook <br/> integrated ");
	    params.putString("description", "");
	    params.putString("link", "https://developers.facebook.com/android");
	    params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
		
		fb.openFeedDialog(this, params);
		

//
//		final WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(this,
//				SimpleFacebook.getOpenSession(), params)).build();
//		feedDialog.show();
		
//		Feed feed = new Feed.Builder()
//				.setMessage("Clone it out...")
//				.setName("Simple Facebook SDK for Android")
//				.setCaption("Code less, do the same.")
//				.setDescription(
//						"The Simple Facebook library project makes the life much easier by coding less code for being able to login, publish feeds and open graph stories, invite friends and more.")
//				.setPicture(
//						"https://raw.github.com/sromku/android-simple-facebook/master/Refs/android_facebook_sdk_logo.png")
//				.setLink("https://github.com/sromku/android-simple-facebook")
//				.build();
//
//		
//		
//		fb.publish(feed, new OnPublishListener() {
//
//			@Override
//			public void onFail(String reason) {
//				dialog.dismiss();
//				onBackPressed();
//			}
//
//			@Override
//			public void onException(Throwable throwable) {
//				dialog.dismiss();
//				onBackPressed();
//			}
//
//			@Override
//			public void onThinking() {
//				dialog = ProgressDialog.show(ShareActivity.this, "Thinking",
//						"Waiting for Facebook", true);
//			}
//
//			@Override
//			public void onComplete(String id) {
//				dialog.dismiss();
//				onBackPressed();
//			}
//		});

	}

}
